import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { PageContiner, Continer } from '@/components';
import { MODULE_NAME, getList } from './redux';
import ProTable from '@ant-design/pro-table';
import { Button, message } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import Organizing from '@/sections/Organizing'
import type { ProColumns } from '@ant-design/pro-table';
import type { ITableListProp, ISearch, IPagination } from './index.d';
import type { IOrganizingProp } from '@/sections/Organizing/index.d'

const BookDetails: React.FC = () => {
  const dispatch = useDispatch();

  const [treeNode, setTreeNode] = useState<{ id: string; nodeType: string; } | null>(null);
  const [loading, setLoading] = useState<boolean>(false);
  const [search, setSearch] = useState<ISearch>({});
  const [pagination, setPagination] = useState<IPagination>({
    page: 1,
    limit: 10
  });

  const { dataSource, total } = useSelector(state => state[MODULE_NAME].tableData);

  const columns: ProColumns<ITableListProp>[] = [{
    title: '学校',
    key: 'schoolId',
    dataIndex: 'schoolName',
    width: 150,
    align: 'center',
    search: false
  }, {
    title: 'ISBN',
    key: 'isbn',
    align: 'center',
    dataIndex: 'isbn',
    width: 150,
    valueType: 'text'
  }, {
    title: '书籍名称',
    key: 'name',
    dataIndex: 'name',
    width: 150,
    align: 'center'
  }, {
    title: '书籍类型',
    key: 'typeName',
    dataIndex: 'typeName',
    width: 100,
    align: 'center',
    search: false
  }, {
    title: '库存数量',
    key: 'number',
    dataIndex: 'number',
    width: 100,
    align: 'center',
    search: false
  }, {
    title: '作者',
    key: 'author',
    dataIndex: 'author',
    width: 150,
    align: 'center'
  }, {
    title: '单价',
    key: 'price',
    dataIndex: 'price',
    width: 100,
    align: 'center',
    search: false
  }, {
    title: '索书号',
    key: 'display',
    dataIndex: 'display',
    width: 150,
    align: 'center'
  }, {
    title: '出版社',
    key: 'publisher',
    dataIndex: 'publisher',
    width: 150,
    align: 'center'
  }, {
    title: '版次',
    key: 'editions',
    dataIndex: 'editions',
    width: 150,
    align: 'center',
    search: false
  }, {
    title: '出版时间',
    key: 'publishTime',
    dataIndex: 'publishTime',
    width: 100,
    align: 'center',
    search: false
  }];


  // 获取列表数据的方法
  const getTableData = async (page: number, limit: number) => {
    setLoading(true)
    await dispatch(getList({
      page,
      limit,
      ...search,
      schoolId: treeNode?.id
    }))
    setLoading(false)
  }

  // 分页变更更新state数据并调用 获取数据方法
  const paginationChange = (page: number, limit: number | undefined) => {
    setPagination({
      page,
      limit: limit || pagination.limit
    });

    getTableData(page, limit || pagination.limit)
  }

  // 搜索条件变更 重置page为1，并变更state数据
  const onSearch = (params: ISearch) => {
    setPagination({
      page: 1,
      limit: pagination.limit
    })
    setSearch(params)
  }

  // 创建 左边树节点点击方法
  const handleClickNode = (keys: string[], node: any) => {
    setPagination({
      page: 1,
      limit: pagination.limit
    })
    setTreeNode({
      id: keys[0],
      nodeType: node.nodeType
    });
  }

  // 导出表格数据
  const downloadSourceData = () => {
    message.warning('该功能正在开发中！')
  }


  // 当 搜索条件和 树节点选中变更的时候 调用获取列表数据方法
  useEffect(() => {
    getTableData(pagination.page, pagination.limit)
  }, [search, treeNode])

  return (
    <PageContiner hiddenBreadcrumb={false}>
      <ProTable<ITableListProp>
        headerTitle="图书列表"
        rowKey="id"
        loading={loading}
        columns={columns}
        bordered
        dataSource={dataSource}
        onSubmit={onSearch}
        onReset={() => onSearch({})}
        scroll={{
          x: 1450,
          y: 'calc(100vh)',
          scrollToFirstRowOnChange: true
        }}
        pagination={{
          "showSizeChanger": true,
          "showQuickJumper": true,
          current: pagination.page,
          pageSize: pagination.limit,
          total: total,
          onChange: paginationChange
        }}
        options={false}
        tableRender={(_, dom) => (
          <Continer
            search
            renderLeft={
              (prop: IOrganizingProp) => <Organizing
                {...prop}
                type="school"
                handleClickNode={handleClickNode}
              />
            }
          >
            {dom}
          </Continer>
        )}
        toolBarRender={() => [
          <Button key="out" onClick={downloadSourceData}>
            导出数据
            <DownloadOutlined />
          </Button>
        ]}
      />
    </PageContiner>
  )
}

export default BookDetails
